<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan, 
 *          Tan Chin Voon, Nazarul Azril
 *
 */

class User extends AppModel {

    /**
     * Defining the name of model
     *
     */
    var $name = 'User';
    /**
     * Defining the name of the table
     *
     */
    var $useTable = 'users';
    /**
     * Displaying user short name
     *
     */
    var $displayName = 'name';
    /**
     * Defining behavior in the model
     *
     */
    var $actsAs = array();
    /**
     * Validating the fields in user model
     */
    var $validate = array(
        'username' => array( 
            'alphaNumeric' => array(
                'rule' => 'alphaNumeric'),
                //'message' => 'Alphabets and numbers only'),
            'minLength'=>array(
                'rule' => array(
                    'minLength',
                    4
                )),
                //'message' => 'Minimum length 4'),
            'Username already taken'=>array(
                'rule' => array(
                    'checkUnique',
                    'username'
                ),
                'on'=>'create',
                //'messsage' =>'Username already taken'
            )
        ),
        'password' => array(
            'alphaNumeric'=> array(
                'rule' => 'alphaNumeric',
                //'message' => 'Alphabets and numbers only'
            ),
            'minLength' => array(
                'rule' => array(
                    'minLength', 4
                ),
                //'message' => 'Minimum length 4'
            )
        ),  
        'name'=>array(
            'required'=>array(
                'rule' => 'notEmpty'
            )
        ),
        'email'=> array(
            'email'=>array(
                'rule' => 'email',
                'required' => true,
                //'message' => 'Invalid email format'
            ),
            'email Unique'=>array(
                'rule' => array(
                    'checkUnique',
                    'email'
                ),
                'required' => true,
                //'message' => 'E-mail already exists'
            )
        ),
        'cc_email'=> array(
            'cc_email'=>array(
                'rule' => 'email',
                'required' => false,
                'allowEmpty'=>true,
            ),
        ),
        'address'=>  array(
            'allowEmpty'=>true,
        ),
        'telephone'=> array(
            'format'=>array(
                'rule' => array(
                    'custom',
                    '/[0-9]{2}[- ]?[0-9]{6,8}$/i'
                ),
                //'required' => true,
                //'message' => 'Telephone required eg: 03-12345213',
                'allowEmpty'=>true
            )
        ),
        'mobile'=> array(
            'format'=>array(
                'rule' => array(
                    'custom','/[0-9]{3}[- ]?[0-9]{7}$/i'
                ),
                //'message' => 'Please supply valid mobile number eg: 013-1234521312',
                'allowEmpty'=>true
            )
        ),
        'fax'=> array(
            'format'=>array(
                'rule' => array(
                    'custom','/[0-9]{2}[- ]?[0-9]{6,8}$/i'
                ),
                //'message' => 'Please supply valid fax number eg: 013-1234521312',
                'allowEmpty'=>true
            )
        )
    );

    //The Associations below have been created with all possible keys, those that are not needed can be removed
    /**
     * Building assosiations betweeen models 
     *
     */
    var $belongsTo = array(
        'Title' => array(
            'className' => 'Title',
            'foreignKey' => 'title_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Protocol' => array(
            'className' => 'Protocol',
            'foreignKey' => 'protocol_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Scheme' => array(
            'className' => 'Scheme',
            'foreignKey' => 'scheme_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    /**
     * Building assosiations betweeen models 
     *
     */
    var $hasMany = array(
        'Announcement' => array(
            'className' => 'Announcement',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'Meetingtodo' => array(
            'className' => 'Meetingtodo',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'Userstatus' => array(
            'className' => 'Userstatus',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'Groupstatus' => array(
            'className' => 'Groupstatus',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
/*remove the user and log relation
        'Log' => array(
            'className' => 'Log',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => 'timestamp',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
*/
    );

    /**
     * Building assosiations betweeen models 
     *
     */
    var $hasAndBelongsToMany = array(
        'Committee' => array(
            'with'=>'Membership'
        ),
        'Meeting' => array(
            'with'=>'Attendance'
        ),
        'Decision' => array(
            'className' => 'Decision',
            'joinTable' => 'decisions_users',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'decision_id',
            'unique' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        ),
        'Group' => array(
            'className' => 'Group',
            'joinTable' => 'users_groups',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'group_id',
            'unique' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        )
    );

    /**
     * Finding all the user data which has the valid login defined in the data
     * $param data finds all the related user data which has a valid login 
     */
    function validateLogin($data){
        $user = $this->find(array('username' => $data['username'], 'password' => md5($data['password']), 'deleted'=>'0'), array('id', 'username','superuser'));
        if(!empty($user))
            return $user['User'];
        return false;
    }

    /**
     * Getting all the user per committee data which has the valid login defined in the data
     * $param data finds all the related user data which has a valid login 
     */
    function getUsersPerCommittee($committee_id,$restrict=false, $meetingId=NULL) { 
        $chairperson = $secretariat = $members = array();
        $users = $this->Membership->find('all',array('conditions'=>array('Membership.committee_id'=>$committee_id, 'User.deleted'=>'0'),'order'=>'Membership.order_id ASC'));
        //$users = $this->Membership->findAll(array('Membership.committee_id'=>$committee_id, 'User.deleted'=>'0'));
        $protocols = $this->Protocol->getProtocolsOnly('','','Protocol.rank ASC');
        $new_users = array();
        //soft the users by protocol
        foreach ( $protocols as $protocol) {
            $user_num = 0;
            foreach ( $users as $user) {
                if ( $protocol['Protocol']['id'] == $user['User']['protocol_id']) {
                    array_push($new_users,$users[$user_num]);
                }//end if
                $user_num++;
            }
        }

        if ( $meetingId ) {
            foreach ($new_users as $new_user) {
                $userQuery = $this->Query("SELECT attend_as FROM attendances WHERE user_id = ".$new_user['Membership']['user_id']." AND meeting_id =".$meetingId);
                //$new_user['Membership']['attend_as'] = isset($userQuery[0]['attendances']['attend_as'])?$userQuery[0]['attendances']['attend_as']:"3";
                $attend_as = isset($userQuery[0]['attendances']['attend_as'])?$userQuery[0]['attendances']['attend_as']:"3";
                
                if ( $attend_as == "2"  ) {
                    $usertitle = $this->Meeting->userlevel($attend_as);
                    $new_user['User']['name'] = $new_user['User']['name']."  ( ".$usertitle." )";
                    array_push($chairperson, $new_user);
                } elseif ( $attend_as == "1"  ) {
                    $usertitle = $this->Meeting->userlevel($attend_as);
                    $new_user['User']['name'] = $new_user['User']['name']."  ( ".$usertitle." )";
                    array_push($secretariat, $new_user);
                } else {
                    array_push($members, $new_user);
                }
            }
            $new_users = array_merge($chairperson, $members, $secretariat);
        }

        //$users = array();//clear users array
        //return $new_users;
        return $users;
    }

    /**
     * Getting list of all the user per committee data defined by the committee_id
     * $param committee_id finds all the related user per committee data
     */
    function getUsersPerCommitteeList($committee_id, $meetingId=NULL) {
        $data=$this->getUsersPerCommittee($committee_id,true, $meetingId);
        $key=Set::extract($data,'{n}.User.id');
        $data=Set::extract($data,'{n}.User.name');
        return array_combine($key,$data);
    }
    /**
     * Create hash if request to reset password
     * $param id ==user_id
     */
    
    function createhash($id) {
        $this->curUser=$id;
        $this->Hash->curUser=$id;
        
        App::import('Model','Hash');
        $this->Hash=& ClassRegistry::init('Hash');
        $e[0]['User']['id'] = $id;
        // save into hash
        $this->Hash->insertToHashTable('password',$e);
    }
    
    
    function afterSave($created) {
        if ($created) {
            // send notification email to user
            App::import('Model',array('Notification','Template'));
            $notify = &new Notification();
            $template = &new Template();
            if (Validation::email($this->data['User']['email'])) {
                $notify->create();
                $data['meeting_id']=0;
                $data['type']='new account';
                $templ=$template->find(array('model'=>'SystemOnly','type'=>$data['type']));
                $data['message_title']=$templ['Template']['title'];
                $data['notification_date']=date('Y-m-d H:i:s');
                
                $replace['name']=$this->data['User']['name'];
                $replace['username']=$this->data['User']['username'];
                $replace['newpassword']=$this->data['User']['password_confirm'];
                $replace['Link']['newaccount']=array('controller'=>'users','action'=>'login');
                $data['message']=$notify->replacetemplate($templ['Template']['template'],$replace);
                $data['to']=$this->data['User']['email'];
                $notify->save($data);
            }
        }
    }
}
?>
